﻿using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Security.Principal;
using Csla;
using System.Data.SqlClient;
using Csla.Data;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace BO.Security
{
    [Serializable()]
    public class BOIdentity :
      ReadOnlyBase<BOIdentity>, IIdentity
    {
        #region Business Methods

        private bool _isAuthenticated;
        private string _name = string.Empty;
        private string _CustomerCode = string.Empty;
        private List<string> _roles = new List<string>();

        public string AuthenticationType
        {
            get { return "Csla"; }
        }

        public bool IsAuthenticated
        {
            get { return _isAuthenticated; }
        }

        public string Name
        {
            get { return _name; }
        }
        protected override object GetIdValue()
        {
            return _name;
        }

        internal bool IsInRole(string role)
        {
            return _roles.Contains(role);
        }

        #endregion

        #region Factory Methods

        internal static BOIdentity UnauthenticatedIdentity()
        {
            return new BOIdentity();
        }

        internal static BOIdentity GetIdentity(
          string username, string password)
        {
            return DataPortal.Fetch<BOIdentity>
              (new Criteria(username, password));
        }

  

        private BOIdentity()
        { /* require use of factory methods */ }

        #endregion

        #region Data Access

        [Serializable()]
        public class Criteria
        {
            private string _username;
            public string Username
            {
                get { return _username; }
            }

            private string _password;
            public string Password
            {
                get { return _password; }
            }

         

            public Criteria(string username, string password)
            {
                _username = username;
                _password = password;
            }

         
        }

        public void DataPortal_Fetch(Criteria criteria)
        {
            //HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/testJson.php");
            //req.Method = "GET";
            //HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //StreamReader rdr = new StreamReader(rsp.GetResponseStream(), Encoding.GetEncoding("GB2312"));
            //string s = rdr.ReadToEnd();

            //var cp = JsonConvert.DeserializeObject<List<dynamic>>(s);
            
            using (DbConnection cn =
              DbFactory.GetConnection(Database.CompanyConnection))
            {
                //cn.Open();
                using (DbCommand cm = cn.CreateCommand())
                {
                    cm.CommandText =string.Format( @"SELECT UserName
	                                FROM SysUser
	                                WHERE IsInactive=0 AND UserName={0}user AND UserPwd={0}pw "
                        ,GlobalVar.Prefix)
                        ;
        
                    cm.Parameters.AddWithValue("user", criteria.Username);
                    cm.Parameters.AddWithValue("pw", criteria.Password);

                    var dit = DataServeice.FecthData(cm);
                  
                        if (dit.Count>0)
                        {
                            _name = criteria.Username;
                            _isAuthenticated = true;
                        }
                        else
                        {
                            _name = string.Empty;
                            
                            _isAuthenticated = GlobalVar.AuthSuperUser(criteria.Username, criteria.Password);
                            if (_isAuthenticated)
                                _name = criteria.Username;
                        }
                    }
            

            }
        }
        #endregion
    }

    [Serializable()]
    public class BOPrincipal : Csla.Security.CslaPrincipal
    {

        private BOPrincipal(IIdentity identity)
            : base(identity) { }

        public static bool Login(string username, string password)
        {
            BOIdentity identity =
              BOIdentity.GetIdentity(username, password);
            if (identity.IsAuthenticated)
            {
                BOPrincipal principal = new BOPrincipal(identity);
                Csla.ApplicationContext.User = principal;
            }
            return identity.IsAuthenticated;
        }

      


        public static void Logout()
        {
            BOIdentity identity = BOIdentity.UnauthenticatedIdentity();
            BOPrincipal principal = new BOPrincipal(identity);
            Csla.ApplicationContext.User = principal;
        }

        public override bool IsInRole(string role)
        {
            BOIdentity identity = (BOIdentity)this.Identity;
            return identity.IsInRole(role);
        }

        public static bool TryLogin()
        {
            BOIdentity identity = BOIdentity.UnauthenticatedIdentity();

            BOPrincipal principal = new BOPrincipal(identity);
            Csla.ApplicationContext.User = principal;

            return identity.IsAuthenticated;
        }
    }
}
